<!-- ChatPanel.vue -->
<!--suppress ALL -->
<template>
  <div class="chat-panel" v-if="currentChat">
    <!-- 聊天头部 -->
    <div class="chat-header">
      <div class="chat-info">
        <el-avatar
            :size="40"
            :src="currentChat.avatar"
            :shape="currentChat.type === 'group' ? 'square' : 'circle'"
        >
          <el-icon v-if="currentChat.type === 'group'"><User /></el-icon>
          <span v-else>{{ currentChat.name?.charAt(0) }}</span>
        </el-avatar>
        <div class="chat-details">
          <div class="chat-title">{{ currentChat.name || currentChat.title }}</div>
          <div class="chat-subtitle">
            <span v-if="currentChat.type === 'private'">
              {{ getRoleText(currentChat.role) }}
            </span>
            <span v-else>
              群聊 · {{ currentChat.participantCount || currentChat.memberCount || 0 }}人
            </span>
          </div>
        </div>
      </div>
      <div class="chat-actions">
        <!-- 查看参与者按钮 -->
        <el-button
            v-if="currentChat.type === 'group'"
            type="text"
            :icon="User"
            @click="showParticipants = true"
            title="查看参与者"
        >
          成员
        </el-button>
<!--        <el-button type="text" :icon="Search" title="搜索聊天记录" />-->
<!--        <el-button type="text" :icon="MoreFilled" title="更多操作" />-->
<!--        <el-button type="text" :icon="Close" @click="closeChat" title="关闭聊天" />-->
      </div>
    </div>

    <!-- 主内容区域 -->
    <div class="chat-main">
      <!-- 聊天内容区域 -->
      <div class="chat-content" ref="chatContentRef">
        <!-- 加载状态 -->
        <div v-if="loadingMessages" class="loading-messages">
          <el-icon class="loading-icon"><Loading /></el-icon>
          <span>加载消息中...</span>
        </div>

        <!-- 消息列表 -->
        <div v-else class="messages-container">
          <!-- 加载更多按钮 -->
          <div v-if="hasMoreMessages" class="load-more-container">
            <el-button
                type="text"
                @click="loadMoreMessages"
                :loading="loadingMore"
                class="load-more-btn"
            >
              加载更多消息
            </el-button>
          </div>

          <div
              v-for="message in messages"
              :key="message.id"
              :class="['message-item', { 'own-message': message.isOwn }]"
          >
            <!-- 对方消息 -->
            <div v-if="!message.isOwn" class="message-left">
              <el-avatar :size="32" :src="message.senderAvatar" class="message-avatar">
                {{ message.senderName?.charAt(0) }}
              </el-avatar>
              <div class="message-content">
                <div v-if="currentChat.type === 'group'" class="message-sender">{{ message.senderName }}</div>
                <div class="message-bubble">
                  <div class="message-text">
                    {{ message.content }}
                  </div>
                  <div v-if="message.sending" class="sending-indicator">
                    <el-icon class="sending-icon"><Loading /></el-icon>
                  </div>
                </div>
                <div class="message-time">{{ formatTime(message.timestamp) }}</div>
              </div>
            </div>

            <!-- 自己发送的消息 -->
            <div v-else class="message-right">
              <div class="message-content">
                <div class="message-bubble own-bubble">
                  <div class="message-text">
                    {{ message.content }}
                  </div>
                  <div v-if="message.sending" class="sending-indicator">
                    <el-icon class="sending-icon"><Loading /></el-icon>
                  </div>
                </div>
                <div class="message-time">{{ formatTime(message.timestamp) }}</div>
              </div>
              <el-avatar :size="32" :src="message.senderAvatar" class="message-avatar">
                {{ message.senderName?.charAt(0) }}
              </el-avatar>
            </div>
          </div>
        </div>
      </div>

      <!-- 参与者侧边栏 -->
      <div v-if="showParticipants && currentChat.type === 'group'" class="participants-sidebar">
        <div class="sidebar-header">
          <span class="sidebar-title">群成员 ({{ participants.length }})</span>
          <el-button type="text" :icon="Close" @click="showParticipants = false" title="关闭" />
        </div>
        <div class="participants-list">
          <div class="search-participant">
            <el-input
                v-model="participantSearch"
                placeholder="搜索成员"
                prefix-icon="Search"
                clearable
                size="small"
            />
          </div>
          <div class="participants-content">
            <!-- 加载状态 -->
            <div v-if="loadingParticipants" class="loading-participants">
              <el-icon class="loading-icon"><Loading /></el-icon>
              <span>加载成员中...</span>
            </div>

            <!-- 成员列表 -->
            <div v-else-if="participants.length > 0">
              <div
                  v-for="participant in filteredParticipants"
                  :key="participant.id"
                  class="participant-item"
              >
                <el-avatar :size="36" :src="participant.avatar" class="participant-avatar">
                  {{ participant.name?.charAt(0) }}
                </el-avatar>
                <div class="participant-info">
                  <div class="participant-name">{{ participant.name }}</div>
                  <div class="participant-role">{{ getRoleText(participant.role) }}</div>
                </div>
                <el-tag v-if="participant.isOwner" size="small" type="success">群主</el-tag>
                <el-tag v-else-if="participant.isAdmin" size="small" type="warning">管理员</el-tag>
              </div>
            </div>

            <!-- 空状态 -->
            <div v-else class="empty-participants">
              暂无成员信息
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="chat-input-area">

      <!-- 输入框 -->
      <div class="input-container">
        <el-input
            v-model="inputMessage"
            type="textarea"
            :rows="3"
            :maxlength="1000"
            placeholder="输入消息..."
            resize="none"
            @keydown="handleKeydown"
            :disabled="sendingMessage"
        />
        <el-button
            type="primary"
            :icon="Promotion"
            :disabled="!inputMessage.trim() || sendingMessage"
            @click="sendMessage"
            class="send-button"
            :loading="sendingMessage"
        >
          {{ sendingMessage ? '发送中' : '发送' }}
        </el-button>
      </div>
    </div>
  </div>

  <!-- 空状态 -->
  <div v-else class="empty-chat">
    <el-empty description="选择一个联系人开始聊天" />
  </div>
</template>
<script setup lang="ts">
import { ref, watch, nextTick, computed, onMounted } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Search,
  MoreFilled,
  Close,
  Picture,
  UploadFilled,
  Promotion,
  User,
  Loading
} from '@element-plus/icons-vue'
import {
  getChatMessages,
  sendChatMessage,
  getChatConversationDetail,
  markChatMessagesAsRead
} from '@/api/teacher'

interface ChatContact {
  id: number
  type: 'private' | 'group'
  name?: string
  title?: string
  avatar?: string
  role?: string
  memberCount?: number
  participantCount?: number
  participants?: any[]
}

interface ChatMessage {
  id: number
  content: string
  senderId: number
  senderName: string
  senderAvatar?: string
  messageType: string
  timestamp: Date
  isOwn: boolean
  conversationId: number
  sending?: boolean
}

interface Participant {
  id: number
  name: string
  avatar?: string
  role: string
  isOwner?: boolean
  isAdmin?: boolean
  joinTime?: Date
}

// Props
interface Props {
  currentChat?: ChatContact | null
}

const props = withDefaults(defineProps<Props>(), {
  currentChat: null
})

// Emits
const emit = defineEmits<{
  'close-chat': []
  'send-message': [message: any]
}>()

// 响应式数据
const inputMessage = ref('')
const messages = ref<ChatMessage[]>([])
const chatContentRef = ref<HTMLElement>()
const showParticipants = ref(false)
const participantSearch = ref('')
const loadingMessages = ref(false)
const loadingMore = ref(false)
const sendingMessage = ref(false)
const loadingParticipants = ref(false)
const currentPage = ref(0)
const hasMoreMessages = ref(true)
const pageSize = 20

// 参与者数据
const participants = ref<Participant[]>([])

// 从本地存储获取当前用户信息
const getCurrentUserInfo = () => {
  const userInfoStr = localStorage.getItem('userInfo')
  if (userInfoStr) {
    try {
      const userInfo = JSON.parse(userInfoStr)
      return {
        id: userInfo.id ? parseInt(userInfo.id) : 1,
        name: userInfo.name || '我',
        avatar: userInfo.avatar,
        role: userInfo.role || 'teacher'
      }
    } catch (error) {
      console.error('解析用户信息失败:', error)
    }
  }
  return { id: 1, name: '我', avatar: '', role: 'teacher' }
}

const currentUser = ref(getCurrentUserInfo())

// 计算属性：过滤后的参与者列表
const filteredParticipants = computed(() => {
  if (!participantSearch.value.trim()) {
    return participants.value
  }
  const searchText = participantSearch.value.toLowerCase()
  return participants.value.filter(participant =>
      participant.name.toLowerCase().includes(searchText)
  )
})

// 监听当前聊天变化
watch(() => props.currentChat, async (newChat) => {
  if (newChat) {
    // 重置消息相关状态
    messages.value = []
    currentPage.value = 0
    hasMoreMessages.value = true

    // 加载聊天记录
    await loadMessages()

    // 如果是群聊，加载群成员
    if (newChat.type === 'group') {
      await loadParticipants(newChat.id)
    }

    // 标记消息为已读
    await markMessagesAsRead(newChat.id)

    scrollToBottom()
    showParticipants.value = false
  } else {
    messages.value = []
    inputMessage.value = ''
    showParticipants.value = false
    participants.value = []
  }
})

// 监听参与者面板显示状态
watch(showParticipants, async (newValue) => {
  if (newValue && props.currentChat?.type === 'group' && participants.value.length === 0) {
    await loadParticipants(props.currentChat.id)
  }
})

// 加载群成员
const loadParticipants = async (conversationId: number) => {
  try {
    loadingParticipants.value = true

    // 首先尝试从当前聊天信息中获取参与者
    if (props.currentChat?.participants && props.currentChat.participants.length > 0) {
      participants.value = props.currentChat.participants.map((p: any) => ({
        id: p.user?.id || p.id,
        name: p.user?.name || p.name || '未知用户',
        avatar: p.user?.avatar || p.avatar,
        role: p.role || 'member',
        isOwner: p.role === 'admin' || p.isOwner,
        isAdmin: p.role === 'admin',
        joinTime: p.joinedAt ? new Date(p.joinedAt) : undefined
      }))
    } else {
      // 如果没有参与者信息，尝试获取会话详情
      const response = await getChatConversationDetail(conversationId)
      if (response.success && response.data.participants) {
        participants.value = response.data.participants.map((p: any) => ({
          id: p.user?.id || p.id,
          name: p.user?.name || p.name || '未知用户',
          avatar: p.user?.avatar || p.avatar,
          role: p.role || 'member',
          isOwner: p.role === 'admin' || p.isOwner,
          isAdmin: p.role === 'admin',
          joinTime: p.joinedAt ? new Date(p.joinedAt) : undefined
        }))
      }
    }
  } catch (error) {
    console.error('加载群成员失败:', error)
    ElMessage.error('加载群成员失败')
  } finally {
    loadingParticipants.value = false
  }
}

// 加载消息
const loadMessages = async () => {
  if (!props.currentChat) return

  try {
    loadingMessages.value = true
    const response = await getChatMessages(props.currentChat.id, currentPage.value, pageSize)

    if (response.success) {
      const newMessages = response.data.content.map((msg: any) => ({
        id: msg.id,
        content: msg.content,
        senderId: msg.sender?.id || msg.senderId,
        senderName: msg.sender?.name || '未知用户',
        senderAvatar: msg.sender?.avatar,
        messageType: msg.messageType || 'text',
        timestamp: new Date(msg.createdAt || msg.timestamp),
        isOwn: (msg.sender?.id || msg.senderId) === currentUser.value.id,
        conversationId: msg.conversationId || props.currentChat?.id,
        sending: false
      }))

      // 如果是第一页，替换所有消息；否则追加到顶部
      if (currentPage.value === 0) {
        messages.value = newMessages.reverse()
      } else {
        messages.value = [...newMessages.reverse(), ...messages.value]
      }

      // 检查是否还有更多消息
      hasMoreMessages.value = !response.data.last

      // 滚动到合适位置
      nextTick(() => {
        if (currentPage.value === 0) {
          scrollToBottom()
        } else {
          // 保持当前位置，不跳转到顶部
          const container = chatContentRef.value
          if (container) {
            const oldScrollHeight = container.scrollHeight
            setTimeout(() => {
              container.scrollTop = container.scrollHeight - oldScrollHeight
            }, 0)
          }
        }
      })
    }
  } catch (error) {
    console.error('加载消息失败:', error)
    ElMessage.error('加载消息失败')
  } finally {
    loadingMessages.value = false
    loadingMore.value = false
  }
}
// 加载更多消息
const loadMoreMessages = async () => {
  if (loadingMore.value || !hasMoreMessages.value) return

  loadingMore.value = true
  currentPage.value += 1
  await loadMessages()
}

// 标记消息为已读
const markMessagesAsRead = async (conversationId: number) => {
  try {
    await markChatMessagesAsRead(conversationId)
  } catch (error) {
    console.error('标记消息已读失败:', error)
  }
}

// 发送消息
const sendMessage = async () => {
  const messageContent = inputMessage.value.trim()
  if (!messageContent || !props.currentChat || sendingMessage.value) return

  try {
    sendingMessage.value = true

    // 先在前端显示发送中的消息（乐观更新）
    const tempMessage: ChatMessage = {
      id: Date.now(), // 临时ID，发送成功后会被替换
      content: messageContent,
      senderId: currentUser.value.id,
      senderName: currentUser.value.name,
      senderAvatar: currentUser.value.avatar,
      messageType: 'text',
      timestamp: new Date(),
      isOwn: true,
      conversationId: props.currentChat.id,
      sending: true
    }

    messages.value.push(tempMessage)
    inputMessage.value = ''
    scrollToBottom()

    // 调用发送消息API
    const messageData = {
      conversationId: props.currentChat.id,
      messageType: 'text',
      content: messageContent
    }

    const response = await sendChatMessage(messageData)

    if (response.success) {
      // 替换临时消息为服务器返回的真实消息
      const index = messages.value.findIndex(msg => msg.id === tempMessage.id)
      if (index !== -1) {
        messages.value[index] = {
          id: response.data.id,
          content: response.data.content,
          senderId: response.data.sender?.id || currentUser.value.id,
          senderName: response.data.sender?.name || currentUser.value.name,
          senderAvatar: response.data.sender?.avatar || currentUser.value.avatar,
          messageType: response.data.messageType || 'text',
          timestamp: new Date(response.data.createdAt || new Date()),
          isOwn: true,
          conversationId: response.data.conversationId || props.currentChat?.id,
          sending: false
        }
      }

      // 通知父组件
      emit('send-message', response.data)

      ElMessage.success('消息发送成功')
    } else {
      // 发送失败，移除临时消息
      const index = messages.value.findIndex(msg => msg.id === tempMessage.id)
      if (index !== -1) {
        messages.value.splice(index, 1)
      }
      ElMessage.error(response.message || '发送消息失败')
    }
  } catch (error) {
    console.error('发送消息失败:', error)

    // 发送失败，移除临时消息
    const tempMessageIndex = messages.value.findIndex(msg => msg.id === Date.now())
    if (tempMessageIndex !== -1) {
      messages.value.splice(tempMessageIndex, 1)
    }

    ElMessage.error('网络错误，发送消息失败')
  } finally {
    sendingMessage.value = false
  }
}

// 处理键盘事件（回车发送）
const handleKeydown = (event: KeyboardEvent) => {
  if (event.key === 'Enter' && !event.shiftKey) {
    event.preventDefault()
    sendMessage()
  }
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (chatContentRef.value) {
      chatContentRef.value.scrollTop = chatContentRef.value.scrollHeight
    }
  })
}

// 关闭聊天
const closeChat = () => {
  emit('close-chat')
}

// 格式化时间显示
const formatTime = (date: Date) => {
  const now = new Date()
  const messageDate = new Date(date)

  // 如果是今天，显示时间
  if (messageDate.toDateString() === now.toDateString()) {
    return messageDate.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit'
    })
  }

  // 如果是昨天，显示"昨天"
  const yesterday = new Date(now)
  yesterday.setDate(yesterday.getDate() - 1)
  if (messageDate.toDateString() === yesterday.toDateString()) {
    return '昨天 ' + messageDate.toLocaleTimeString('zh-CN', {
      hour: '2-digit',
      minute: '2-digit'
    })
  }

  // 其他情况显示完整日期
  return messageDate.toLocaleDateString('zh-CN') + ' ' +
      messageDate.toLocaleTimeString('zh-CN', {
        hour: '2-digit',
        minute: '2-digit'
      })
}

// 获取角色文本
const getRoleText = (role?: string) => {
  const roleMap: Record<string, string> = {
    'student': '学生',
    'teacher': '老师',
    'admin': '管理员',
    'member': '成员'
  }
  return roleMap[role || ''] || '用户'
}
</script>
<style scoped>
.chat-panel {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #fff;
}

/* 聊天头部 */
.chat-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  border-bottom: 1px solid #e4e7ed;
  background: #fafafa;
}

.chat-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.chat-details {
  display: flex;
  flex-direction: column;
}

.chat-title {
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 2px;
}

.chat-subtitle {
  font-size: 12px;
  color: #909399;
}

.chat-actions {
  display: flex;
  gap: 8px;
}

/* 主内容区域 */
.chat-main {
  flex: 1;
  display: flex;
  overflow: hidden;
}

/* 聊天内容区域 */
.chat-content {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  background: #f5f5f5;
  transition: all 0.3s ease;
}

.loading-messages {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
  color: #909399;
  gap: 8px;
}

.load-more-container {
  display: flex;
  justify-content: center;
  padding: 10px 0;
}

.load-more-btn {
  color: #409eff;
}

.messages-container {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.message-item {
  display: flex;
}

.message-left {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  max-width: 70%;
}

.message-right {
  display: flex;
  align-items: flex-start;
  justify-content: flex-end;
  gap: 8px;
  max-width: 70%;
  margin-left: auto;
}

.message-avatar {
  flex-shrink: 0;
}

.message-content {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.message-sender {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.message-bubble {
  background: #fff;
  padding: 12px 16px;
  border-radius: 18px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.1);
  max-width: 100%;
  word-wrap: break-word;
  position: relative;
}

.own-bubble {
  background: #409eff;
  color: #fff;
}

.message-text {
  font-size: 14px;
  line-height: 1.4;
}

.sending-indicator {
  display: inline-flex;
  align-items: center;
  margin-left: 8px;
}

.sending-icon {
  font-size: 12px;
  animation: rotate 1s linear infinite;
}

.message-time {
  font-size: 11px;
  color: #c0c4cc;
  text-align: right;
}

.message-left .message-time {
  text-align: left;
}

/* 参与者侧边栏 */
.participants-sidebar {
  width: 280px;
  border-left: 1px solid #e4e7ed;
  background: #fff;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  border-bottom: 1px solid #e4e7ed;
  background: #fafafa;
}

.sidebar-title {
  font-size: 14px;
  font-weight: 600;
  color: #303133;
}

.participants-list {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.search-participant {
  padding: 16px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.participants-content {
  flex: 1;
  overflow-y: auto;
  padding: 8px 0;
}

.loading-participants {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 40px;
  color: #909399;
  gap: 8px;
}

.empty-participants {
  padding: 40px;
  text-align: center;
  color: #909399;
}

.participant-item {
  display: flex;
  align-items: center;
  padding: 12px 20px;
  gap: 12px;
  transition: background-color 0.3s;
}

.participant-item:hover {
  background-color: #f5f7fa;
}

.participant-avatar {
  flex-shrink: 0;
}

.participant-info {
  flex: 1;
  min-width: 0;
}

.participant-name {
  font-size: 14px;
  color: #303133;
  margin-bottom: 2px;
  font-weight: 500;
}

.participant-role {
  font-size: 12px;
  color: #909399;
}

/* 输入区域 */
.chat-input-area {
  border-top: 1px solid #e4e7ed;
  background: #fff;
}

.toolbar {
  padding: 8px 20px;
  border-bottom: 1px solid #f0f0f0;
}

.input-container {
  display: flex;
  padding: 16px 20px;
  gap: 12px;
  align-items: flex-end;
}

.input-container :deep(.el-textarea) {
  flex: 1;
}

.input-container :deep(.el-textarea__inner) {
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  padding: 12px;
  font-size: 14px;
}

.send-button {
  align-self: flex-end;
  height: auto;
  padding: 8px 16px;
}

/* 空状态 */
.empty-chat {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #fafafa;
}

/* 滚动条样式 */
.chat-content::-webkit-scrollbar,
.participants-content::-webkit-scrollbar {
  width: 6px;
}

.chat-content::-webkit-scrollbar-track,
.participants-content::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.chat-content::-webkit-scrollbar-thumb,
.participants-content::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.chat-content::-webkit-scrollbar-thumb:hover,
.participants-content::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

.loading-icon {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>
